package com.deli.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Iterator;

public class XmlUtil {

    public static String readStringXml(String xml, String elementName) {
        String elementValue = null;
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            //System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Iterator iter = rootElt.elementIterator("UserBean"); // 获取根节点下的子节点head

            // 遍历head节点
            // 遍历Header节点下的Response节点
            while (iter.hasNext()) {
                Element itemEle = (Element) iter.next();
                elementValue = itemEle.elementTextTrim(elementName); // 拿到head下的子节点script下的字节点username的值
                //System.out.println("查到的元素值是:" + elementValue);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return elementValue;
        }
    }
}

